<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三角</title>
</head>
<body>

<canvas id="webgl" width="400" height="400"></canvas>

<script>
(function() {
var canvas = document.getElementById('webgl');
var gl = canvas.getContext('webgl');


// 1. 准备 shader
var VSHADER_SOURCE =
    `attribute vec4 a_Position;
    void main() {
        gl_Position = a_Position;
        // 如果是画点 这个变量必须指定
        // gl_PointSize = 10.0;
    }`;
var FSHADER_SOURCE =
    `void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }`;

var vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, VSHADER_SOURCE);
gl.compileShader(vShader);

var fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, FSHADER_SOURCE);
gl.compileShader(fShader);


// 2. 准备程序
var program = gl.createProgram();
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
gl.useProgram(program);
gl._program = program;


// 3. 向 attribute 传值
var attributeAddress = gl.getAttribLocation(gl._program, 'a_Position');
var buffer = gl.createBuffer();
// 将创建的 buffer 绑定到 webgl 的 ARRAY_BUFFER 上
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
    0.0, 0.5,
    -0.5, -0.5,
    0.5, -0.5
]), gl.STATIC_DRAW);
// 给 attribute 变量赋值
gl.vertexAttribPointer(attributeAddress, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(attributeAddress);


// 指定清空 canvas 的颜色
gl.clearColor(0, 0, 0, .6);
// 清空 canvas
gl.clear(gl.COLOR_BUFFER_BIT);
// 绘制
gl.drawArrays(gl.TRIANGLES, 0, 3);

})();
</script>
</body>
</html>
